#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import subprocess
from ...._util import Util
from ...._plugin import KernelAddonPlugin


class Plugin(KernelAddonPlugin):

    __url = "https://apt.bcachefs.org/unstable/pool/main/b/bcachefs-tools"

    __verFile = "bcachefs.versions"

    def sync(self, context):
        v = MyUtil.getNewestVersionFromHyperlinks("linux-addon/bcachefs", self.__url, "bcachefs-kernel-dkms_([0-9\\.]+)_.*\\.deb")[0]
        with context.distfiles_open_for_write(self.__verFile) as f:
            f.write(v + "\n")

    def list_versions(self, context):
        return Util.readListFile(context.distfiles_get(self.__verFile))

    def list_distfiles(self, context):
        return [context.distfiles_fn(self._localFn(x)) for x in context.versions]

    def fetch(self, context):
        for version in context.versions:
            context.distfiles_download(os.path.join(self.__url, self._localFn(version)))

    def unpack(self, context):
        localFullfn = context.distfiles_get(self._localFn(context.version))
        Util.extractDeb(localFullfn, "xz")

    def install(self, context):
        # using shell=True, since "make" is too old, for example it may reads bash $PWD instead of using working directory of OS
        makeOpts = context.get_build_variable("MAKEOPTS")
        subprocess.check_call("make %s > make-bcachefs.log" % (makeOpts), shell=True)
        subprocess.check_call("make %s install > make-bcachefs-install.log" % (makeOpts), shell=True)

    def _localFn(self, version):
        return "bcachefs-kernel-dkms_%s_amd64.deb" % (version)


class MyUtil:

    @staticmethod
    def getNewestVersionFromHyperlinks(myName, url, pattern):
        ver = None
        href = None
        root = Util.fetchAndParseHtmlPage(myName, url)
        for atag in root.xpath(".//a"):
            if atag.text is None:
                # it's really strange that a.text can be None
                continue
            m = re.fullmatch(pattern, atag.text.strip())
            if m is not None:
                if ver is None or MyUtil.compareVersion(ver, m.group(1)) < 0:
                    ver = m.group(1)
                    href = atag.get("href")
        return (ver, href)

    @staticmethod
    def compareVersion(verstr1, verstr2):
        """eg: 3.9.11-gentoo-r1 or 3.10.7-gentoo"""

        partList1 = verstr1.split("-")
        partList2 = verstr2.split("-")

        verList1 = partList1[0].split(".")
        verList2 = partList2[0].split(".")

        if len(verList1) == 4:
            ver1 = int(verList1[0]) * 1000000 + int(verList1[1]) * 10000 + int(verList1[2]) * 100 + int(verList1[3])
        elif len(verList1) == 3:
            ver1 = int(verList1[0]) * 1000000 + int(verList1[1]) * 10000 + int(verList1[2]) * 100
        elif len(verList1) == 2:
            ver1 = int(verList1[0]) * 1000000 + int(verList1[1]) * 10000
        elif len(verList1) == 1:
            ver1 = int(verList1[0]) * 1000000
        else:
            assert False

        if len(verList2) == 4:
            ver2 = int(verList2[0]) * 1000000 + int(verList2[1]) * 10000 + int(verList2[2]) * 100 + int(verList2[3])
        elif len(verList2) == 3:
            ver2 = int(verList2[0]) * 1000000 + int(verList2[1]) * 10000 + int(verList2[2]) * 100
        elif len(verList2) == 2:
            ver2 = int(verList2[0]) * 1000000 + int(verList2[1]) * 10000
        elif len(verList2) == 1:
            ver2 = int(verList2[0]) * 1000000
        else:
            assert False

        if ver1 > ver2:
            return 1
        elif ver1 < ver2:
            return -1

        if len(partList1) >= 2 and len(partList2) == 1:
            return 1
        elif len(partList1) == 1 and len(partList2) >= 2:
            return -1

        p1 = "-".join(partList1[1:])
        p2 = "-".join(partList2[1:])
        if p1 > p2:
            return 1
        elif p1 < p2:
            return -1

        return 0
